package com.sptpc.qimoxiangmu.service;


import com.sptpc.qimoxiangmu.model.Type;
import com.sptpc.qimoxiangmu.model.vo.TypeVo;
import com.sptpc.qimoxiangmu.repository.TypeRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class TypeService {
    @Autowired
    private TypeRepository categoryRepository;
    public Type saveCategory(String name){
        return categoryRepository.save(Type.builder().name(name).build());
    }
    public Type saveCategory(Type category){
        return categoryRepository.save(category);
    }
    //更新
    public Type update(Long id, String newName){
        Optional<Type> oldCatgroy=categoryRepository.findById(id);
        if (oldCatgroy.isPresent()){
            Type category=oldCatgroy.get();
            category.setName(newName);
            return categoryRepository.saveAndFlush(category);
        }else{
            return null;
        }

    }
    //通过表单对象更新，前端
    public Type update(TypeVo categoryVo){
        Optional<Type> oldCategroy=categoryRepository.findById(categoryVo.getId());
        if (oldCategroy.isPresent()){
            Type category=oldCategroy.get();
            category.setName(categoryVo.getName());
            return categoryRepository.saveAndFlush(category);
        }else{
            return null;
        }
    }
    public List<Type> findAll(){
        return categoryRepository.findAll(Sort.by(Sort.Direction.DESC, "updateTime"));//排序加所有查询DES为降序
    }
    public Type findOne(String name){
//        ExampleMatcher matcher =ExampleMatcher.matching()
//                .withIgnoreCase("name");
//        Example example = Example.of(Category.builder().name(name).build(),matcher);
        Optional<Type> category =categoryRepository.findByName(name);
        if(category.isPresent()){
            return  category.get();
        }
        return  null;
    }
    public Type findOne(Long id){
        Optional<Type> category =categoryRepository.findById(id);
        if(category.isPresent()){
            return  category.get();
        }
        return  null;
    }
    public Type findOneLike(String name){
        Optional<Type> category =categoryRepository.findByNameLike(name);
        if(category.isPresent()){
            return category.get();
        }else {
            return null;
        }
    }
//    通过name删除
    public Boolean delete(String name){
        Optional<Type> category =categoryRepository.findByName(name);
        if (category.isPresent()){
            categoryRepository.delete(category.get());
            return true;
        }else {
            return false;
        }
        }
    //通过id删除
    public void deleteCategory(Long id){
        categoryRepository.deleteById(id);
    }
}
